<template>
  <page-view class="page-view page-view-container" :title="false">
    <div slot="headerContent">
      <div class="title">部门管理</div>
    </div>

    <a-row :gutter="10">
      <a-col :md="12" :sm="24">
        <a-card :bordered="false" class="s-card">
          <!-- 按钮操作区域 -->
          <a-row style="margin-left: 14px" class="button-container">
            <!-- <a-button type="primary" @click="handleAdd(2)">添加子部门</a-button> -->
            <a-button type="primary" @click="handleAdd(1)">添加一级部门</a-button>
            <a-button type="primary" @click="handleAdd(2)">添加子部门</a-button>
            <!-- <a-button type="primary" icon="download" @click="handleExportXls('部门信息')">导出</a-button>
          <a-upload name="file" :show-upload-list="false" :multiple="false" :action="importExcelUrl" @change="handleImportExcel">
            <a-button type="primary" icon="import">导入</a-button>
          </a-upload> -->
            <a-button title="删除多条数据" type="default" @click="batchDel">批量删除</a-button>
            <!--<a-button @click="refresh" type="default" icon="reload" :loading="loading">刷新</a-button>-->
          </a-row>
          <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
            <a-alert type="info" :show-icon="true">
              <div slot="message">
                当前选择：
                <a v-if="this.currSelected.title">{{ getCurrSelectedTitle() }}</a>
                <a v-if="this.currSelected.title" style="margin-left: 10px" @click="onClearSelected">取消选择</a>
              </div>
            </a-alert>
            <a-input-search style="width:100%;margin-top: 10px" placeholder="请输入部门名称" @search="onSearch" />
            <!-- 树-->
            <a-col :md="10" :sm="24">
              <template>
                <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                  <span style="user-select: none">
                    <a-tree
                      checkable
                      multiple
                      :selected-keys="selectedKeys"
                      :checked-keys="checkedKeys"
                      :tree-data="departTree"
                      :check-strictly="true"
                      :expanded-keys="iExpandedKeys"
                      :auto-expand-parent="autoExpandParent"
                      @select="onSelect"
                      @check="onCheck"
                      @rightClick="rightHandle"
                      @expand="onExpand"
                    />
                  </span>
                  <!--新增右键点击事件,和增加添加和删除功能-->
                  <a-menu slot="overlay">
                    <a-menu-item key="1" @click="handleAdd(3)">添加</a-menu-item>
                    <a-menu-item key="2" @click="handleDelete">删除</a-menu-item>
                    <a-menu-item key="3" @click="closeDrop">取消</a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </a-col>
          </div>
        </a-card>
      </a-col>
      <a-col :md="12" :sm="24">
        <a-card :bordered="false" class="s-card">
          <a-form :form="form">
            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="机构名称"
            >
              <a-input v-decorator="['departName', validatorRules.departName ]" placeholder="请输入机构/部门名称" />
            </a-form-item>
            <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="上级部门">
              <a-tree-select
                v-model="model.parentId"
                style="width:100%"
                :dropdown-style="{maxHeight:'200px',overflow:'auto'}"
                :tree-data="treeData"
                :disabled="disable"
                placeholder="无"
              />
            </a-form-item>
            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="机构编码"
            >
              <a-input v-decorator="['orgCode', validatorRules.orgCode ]" disabled placeholder="请输入机构编码" />
            </a-form-item>
            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="排序"
            >
              <a-input-number v-decorator="[ 'departOrder',{'initialValue':0}]" />
            </a-form-item>

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="分组名"
            >
              <a-input v-decorator="['groupName', {'initialValue':''}]" placeholder="请输入分组名" />
            </a-form-item>

            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="手机号"
            >
              <a-input v-decorator="['mobile', {'initialValue':''}]" placeholder="请输入手机号" />
            </a-form-item>
            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="地址"
            >
              <a-input v-decorator="['address', {'initialValue':''}]" placeholder="请输入地址" />
            </a-form-item>
            <a-form-item
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
              label="备注"
            >
              <a-textarea v-decorator="['memo']" placeholder="请输入备注" />
            </a-form-item>
          </a-form>
          <div class="anty-form-btn">
            <a-button type="default" html-type="button" icon="sync" @click="emptyCurrForm">重置</a-button>
            <a-button type="primary" html-type="button" icon="form" @click="submitCurrForm">修改</a-button>
            <a-button v-if="parentId === 0" type="primary" html-type="button" icon="form" @click="handleSalaryEdit">薪资构成</a-button>
          </div>
        </a-card>
      </a-col>
      <depart-modal ref="departModal" @ok="loadTree" />
    </a-row>

    <SalaryDepartmentRelationSave
      v-if="salaryEdit"
      ref="SalaryDepartmentRelationSave"
      :data="salaryEditForm"
      @refreshDataList="salaryEdit = false"
      @dialogClosed="salaryEdit = false"
    />

  </page-view>
</template>
<script>
import { PageView } from '@/components'
import DepartModal from './modules/DepartModal'
import SalaryDepartmentRelationSave from '@/pages/salary/SalaryDepartmentRelationSave'
import pick from 'lodash.pick'
// import { queryDepartTreeList, searchByKeywords, deleteByDepartId } from '@/api/api'
import { skylineListMixin } from '@/pages/mixins/skylineListMixin'
// 表头
const columns = [
  {
    title: '机构名称',
    dataIndex: 'departName'
  },
  {
    title: '机构类型',
    align: 'center',
    dataIndex: 'orgType'
  },
  {
    title: '机构编码',
    dataIndex: 'orgCode'
  },
  {
    title: '手机号',
    dataIndex: 'mobile'
  },
  {
    title: '传真',
    dataIndex: 'fax'
  },
  {
    title: '地址',
    dataIndex: 'address'
  },
  {
    title: '排序',
    align: 'center',
    dataIndex: 'departOrder'
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'DepartList',
  components: {
    PageView,
    DepartModal,
    SalaryDepartmentRelationSave
  },
  layout: 'basic-layout',
  mixins: [skylineListMixin],
  data () {
    return {
      id: null,
      parentId: null,
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      disable: true,
      treeData: [],
      visible: false,
      departTree: [],
      rightClickSelectedKey: '',
      hiding: true,
      model: {},
      dropTrigger: '',
      depart: {},
      columns: columns,
      disableSubmit: false,
      checkedKeys: [],
      selectedKeys: [],
      autoIncr: 1,
      currSelected: {},
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      graphDatasource: {
        nodes: [],
        edges: []
      },
      validatorRules: {
        departName: { rules: [{ required: true, message: '请输入机构/部门名称!' }] },
        orgCode: { rules: [{ required: true, message: '请输入机构编码!' }] },
        mobile: { rules: [{ validator: this.validateMobile }] }
      },
      url: {
        delete: '/sysdepart/sysDepart/delete',
        edit: '/sysdepart/sysDepart/edit',
        deleteBatch: '/sysdepart/sysDepart/deleteBatch'
      },
      salaryEdit: false,
      salaryEditForm: {}
    }
  },
  computed: {

  },
  created () {
    this.id = null
    this.parentId = null
    this.currFlowId = this.$route.params.id
    this.currFlowName = this.$route.params.name
    // this.loadTree()
  },
  methods: {
    loadData () {
      this.refresh()
    },
    loadTree () {
      var that = this
      that.treeData = []
      that.departTree = []
      that.$authApi.queryDepartTreeList().then((res) => {
        if (res.code === '000000') {
          for (let i = 0; i < res.data.length; i++) {
            const temp = res.data[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
            console.log(temp.id)
          }
          this.loading = false
        }
      })
    },
    setThisExpandedKeys (node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh () {
      this.loading = true
      this.loadTree()
    },
    // 右键操作方法
    rightHandle (node) {
      this.dropTrigger = 'contextmenu'
      console.log(node.node.eventKey)
      this.rightClickSelectedKey = node.node.eventKey
    },
    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    backFlowList () {
      this.$router.back(-1)
    },
    // 右键点击下拉框改变事件
    dropStatus (visible) {
      if (visible === false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop () {
      this.dropTrigger = ''
    },
    addRootNode () {
      this.$refs.nodeModal.add(this.currFlowId, '')
    },
    batchDel: function () {
      console.log(this.checkedKeys)
      if (this.checkedKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
      } else {
        var ids = ''
        for (var a = 0; a < this.checkedKeys.length; a++) {
          ids += this.checkedKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '确定要删除所选中的 ' + this.checkedKeys.length + ' 条数据?',
          onOk: function () {
            that.$authApi.deleteDepartBatch(ids).then((res) => {
              if (res.code === '000000') {
                that.$message.success(res.mesg)
                that.loadTree()
                that.onClearSelected()
              } else {
                that.$message.warning(res.mesg)
              }
            })
          }
        })
      }
    },
    onSearch (value) {
      const that = this
      if (value) {
        that.$authApi.searchByKeywords(value).then((res) => {
          if (res.code === '000000') {
            that.departTree = []
            for (let i = 0; i < res.data.length; i++) {
              const temp = res.data[i]
              that.departTree.push(temp)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        that.loadTree()
      }
    },
    nodeModalOk () {
      this.loadTree()
    },
    nodeModalClose () {
    },
    hide () {
      console.log(111)
      this.visible = false
    },
    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.hiding = false
      this.checkedKeys = checkedKeys.checked
    },
    onSelect (selectedKeys, e) {
      console.log('selected', selectedKeys, e)
      this.hiding = false
      const record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.model = this.currSelected
      this.selectedKeys = [record.key]
      this.model.parentId = record.parentId
      this.setValuesToForm(record)
    },
    // 触发onSelect事件时,为部门树右侧的form表单赋值
    setValuesToForm (record) {
      this.id = record.intId
      this.parentId = record.intParentId
      this.form.getFieldDecorator('fax', { initialValue: '' })
      record.mobile = record.mobile === null ? '' : record.mobile
      record.address = record.address === null ? '' : record.address
      record.memo = record.memo === null ? '' : record.memo
      record.groupName = record.groupName === null ? '' : record.groupName
      this.form.setFieldsValue(pick(record, 'departName', 'orgCode', 'departOrder', 'mobile', 'fax', 'address', 'memo', 'groupName'))
    },
    getCurrSelectedTitle () {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected () {
      this.hiding = true
      this.checkedKeys = {}
      this.currSelected = {}
      this.form.resetFields()
      this.selectedKeys = []
    },
    handleNodeTypeChange (val) {
      this.currSelected.nodeType = val
    },
    notifyTriggerTypeChange (value) {
      this.currSelected.notifyTriggerType = value
    },
    receiptTriggerTypeChange (value) {
      this.currSelected.receiptTriggerType = value
    },
    submitCurrForm () {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (!this.currSelected.id) {
            this.$message.warning('请点击选择要修改部门!')
            return
          }

          const formData = Object.assign(this.currSelected, values)
          console.log('Received values of form: ', formData)
          formData.createTime = null
          this.$authApi.editDept(formData).then((res) => {
            if (res.code === '000000') {
              this.$message.success('保存成功!')
              this.loadTree()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    emptyCurrForm () {
      this.form.resetFields()
    },
    nodeSettingFormSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
        }
      })
    },
    openSelect () {
      this.$refs.sysDirectiveModal.show()
    },
    handleAdd (num) {
      if (num === 1) {
        this.$refs.departModal.add()
        this.$refs.departModal.title = '新增'
      } else if (num === 2) {
        const key = this.currSelected.key
        if (!key) {
          this.$message.warning('请先选中一条记录!')
          return false
        }
        this.$refs.departModal.add(this.selectedKeys)
        this.$refs.departModal.title = '新增'
      } else {
        this.$refs.departModal.add(this.rightClickSelectedKey)
        this.$refs.departModal.title = '新增'
      }
    },
    handleDelete () {
      this.$authApi.deleteByDepartId(this.rightClickSelectedKey).then((resp) => {
        if (resp.code === '000000') {
          this.$message.success('删除成功!')
          this.loadTree()
        } else {
          this.$message.warning('删除失败!')
        }
      })
    },
    selectDirectiveOk (record) {
      console.log('选中指令数据', record)
      this.nodeSettingForm.setFieldsValue({ directiveCode: record.directiveCode })
      this.currSelected.sysCode = record.sysCode
    },
    getFlowGraphData (node) {
      this.graphDatasource.nodes.push({
        id: node.id,
        text: node.flowNodeName
      })
      if (node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          const temp = node.children[a]
          this.graphDatasource.edges.push({
            source: node.id,
            target: temp.id
          })
          this.getFlowGraphData(temp)
        }
      }
    },
    handleSalaryEdit () {
      if (!this.id) {
        this.$message.warning('请点击选择要修改部门!')
        return
      }
      this.salaryEdit = true
      this.salaryEditForm = { id: this.id }
    }
  }

}
</script>
<style scoped lang="less">
  .ant-card-body .table-operator {
    margin: 15px;
  }

  .anty-form-btn {
    width: 100%;
    text-align: center;
  }

  .anty-form-btn button {
    margin: 0 5px;
  }

  .anty-node-layout .ant-layout-header {
    padding-right: 0
  }

  .header {
    padding: 0 8px;
  }

  .header button {
    margin: 0 3px
  }

  .ant-modal-cust-warp {
    height: 100%
  }

  .ant-modal-cust-warp .ant-modal-body {
    height: calc(100% - 110px) !important;
    overflow-y: auto
  }

  .ant-modal-cust-warp .ant-modal-content {
    height: 90% !important;
    overflow-y: hidden
  }

  #app .desktop {
    height: auto !important;
  }

  /** Button按钮间距 */
  .ant-btn {
    margin-left: 3px
  }

  .button-container {
    button {
      margin-bottom: 12px;
    }
  }

</style>
